/**
 * Enhanced Calendar Main JS file
 *
 * @access      public
 * @author      Rob Locke
 * @copyright   ResMania 2011 all rights reserved.
 * @version     1.0
 * @link        http://docs.resmania.com/index.php?title=Enhanced_Calendar
 * @since       03-2011
 * @notes       jslint:
 */

Ext.onReady(function(){

    RM.Pages.EnhancedCalendar_SelectedView = 3; // week view as the initial view

    Ext.override(Ext.ensible.cal.EventContextMenu,{
        /**
         * override the calendar event context menu (right click)
         */
        buildMenu: function(){
            Ext.apply(this, {
                items: []
            });
        }
    });

    Ext.override(Ext.ensible.cal.DateRangeField,{
        onRender: function(ct, position){
            if(!this.el){

                // this is passed from the price system, if the price system does
                // allow hourly selection then we disable it here.
                this.showTimes = show_time;

                this.startDate = new Ext.form.DateField({
                    id: this.id+'-start-date',
                    format: this.dateFormat,
                    width:100,
                    listeners: {
                        'change': {
                            fn: function(){
                                this.onFieldChange('date', 'start');
                            },
                            scope: this
                        }
                    }
                });
                this.startTime = new Ext.form.TimeField({
                    id: this.id+'-start-time',
                    hidden: this.showTimes === false,
                    labelWidth: 0,
                    hideLabel:true,
                    width:90,
                    listeners: {
                        'select': {
                            fn: function(){
                                this.onFieldChange('time', 'start');
                            },
                            scope: this
                        }
                    }
                });
                this.endTime = new Ext.form.TimeField({
                    id: this.id+'-end-time',
                    hidden: this.showTimes === false,
                    labelWidth: 0,
                    hideLabel:true,
                    width:90,
                    listeners: {
                        'select': {
                            fn: function(){
                                this.onFieldChange('time', 'end');
                            },
                            scope: this
                        }
                    }
                });
                this.endDate = new Ext.form.DateField({
                    id: this.id+'-end-date',
                    format: this.dateFormat,
                    hideLabel:true,
                    width:100,
                    listeners: {
                        'change': {
                            fn: function(){
                                this.onFieldChange('date', 'end');
                            },
                            scope: this
                        }
                    }
                });
                this.allDay = new Ext.form.Checkbox({
                    id: this.id+'-allday',
                    hidden: this.showTimes === false || this.showAllDay === false,
                    boxLabel: this.allDayText,
                    handler: function(chk, checked){
                        this.startTime.setVisible(!checked);
                        this.endTime.setVisible(!checked);
                    },
                    scope: this
                });
                this.toLabel = new Ext.form.Label({
                    xtype: 'label',
                    id: this.id+'-to-label',
                    text: this.toText
                });

                var singleLine = this.singleLine;
                if(singleLine === 'auto'){
                    var el, w = this.ownerCt.getWidth() - this.ownerCt.getEl().getPadding('lr');
                    if(el = this.ownerCt.getEl().child('.x-panel-body')){
                        w -= el.getPadding('lr');
                    }
                    if(el = this.ownerCt.getEl().child('.x-form-item-label')){
                        w -= el.getWidth() - el.getPadding('lr');
                    }
                    singleLine = w <= this.singleLineMinWidth ? false : true;
                }

                this.fieldCt = new Ext.Container({
                    autoEl: {id:this.id}, //make sure the container el has the field's id
                    cls: 'ext-dt-range',
                    renderTo: ct,
                    layout: 'table',
                    layoutConfig: {
                        columns: singleLine ? 6 : 3
                    },
                    defaults: {
                        hideParent: true
                    },
                    items:[
                        this.startDate,
                        this.startTime,
                        this.toLabel,
                        singleLine ? this.endTime : this.endDate,
                        singleLine ? this.endDate : this.endTime,
                        this.allDay
                    ]
                });

                this.fieldCt.ownerCt = this;
                this.el = this.fieldCt.getEl();
                this.items = new Ext.util.MixedCollection();
                this.items.addAll([this.startDate, this.endDate, this.toLabel, this.startTime, this.endTime, this.allDay]);
            }

            Ext.ensible.cal.DateRangeField.superclass.onRender.call(this, ct, position);

            if(!singleLine){
                this.el.child('tr').addClass('ext-dt-range-row1');
            }
        }
    });

   // override the Extensibe Calendar to provide our own new reservsstion form.
    Ext.override(Ext.ensible.cal.EventEditWindow,{
        onRender : function(ct, position){

            this.titleTextAdd = RM.Translate.User.EnhancedCalendar.NewReservation;

            this.deleteBtn = Ext.getCmp(this.id+'-delete-btn');
                       
            this.titleField = new Ext.form.TextField({
                name: Ext.ensible.cal.EventMappings.Title.name,
                fieldLabel: this.titleLabelText,
                anchor: '100%'
            });

            this.dateRangeField = new Ext.ensible.cal.DateRangeField({
                anchor: '95%',
                fieldLabel: this.datesLabelText,
                dateFormat: RM.Common.GUIDateFormat
            });

            var items = [this.dateRangeField];

            var hidePersonsFeildset = false;

            // persons selection
            if (adults>1){
                // adults

                hidePersonsFeildset = true;

                this.adultsField = new Ext.form.ComboBox ({
                    id : "adultsValue",
                    name : "adultsValue_name",
                    hiddenName : "adultsValue_hidden",
                    width : 50,
                    triggerAction: 'all',
                    fieldLabel : RM.Translate.User.EnhancedCalendar.Adults,
                    store : new Ext.data.SimpleStore({
                        fields:[
                        {
                            name:'value',
                            type:'string'
                        },

                        {
                            name:'text',
                            type:'string'
                        }
                        ],
                        data: RM.Common.Combo_Number_Data(1,adults,1)
                    }),
                    value: 1,
                    mode: 'local',
                    typeAhead: true,
                    resizable: false,
                    valueField: 'value',
                    displayField: 'text'
                });

            } else {
                this.adultsField = new Ext.form.Hidden ({
                    id : "adultsValue",
                    value: 1
                });
            }

            // children
            if (children>0){
                this.childrenField = new Ext.form.ComboBox ({
                    id : "childrenValue",
                    name : "childrenValue_name",
                    hiddenName : "childrenValue_hidden",
                    width : 50,
                    triggerAction: 'all',
                    fieldLabel : RM.Translate.User.EnhancedCalendar.Children,
                    store : new Ext.data.SimpleStore({
                        fields:[
                        {
                            name:'value',
                            type:'string'
                        },

                        {
                            name:'text',
                            type:'string'
                        }
                        ],
                        data: RM.Common.Combo_Number_Data(1,children,1)
                    }),
                    mode: 'local',
                    typeAhead: true,
                    resizable: false,
                    valueField: 'value',
                    displayField: 'text',
                    value: 0
                });


            } else {
                this.childrenField = new Ext.form.Hidden ({
                    id : "childrenValue",
                    value: 0
                });
            }

            // infants
            if (infants>0){
                this.infantsField = new Ext.form.ComboBox ({
                    id : "infantsValue",
                    name : "infantsValue_name",
                    hiddenName : "infantsValue_hidden",
                    width : 50,
                    triggerAction: 'all',
                    fieldLabel : RM.Translate.User.EnhancedCalendar.Infants,
                    store : new Ext.data.SimpleStore({
                        fields:[
                        {
                            name:'value',
                            type:'string'
                        },

                        {
                            name:'text',
                            type:'string'
                        }
                        ],
                        data: RM.Common.Combo_Number_Data(1,infants,1)
                    }),
                    mode: 'local',
                    typeAhead: true,
                    resizable: false,
                    valueField: 'value',
                    displayField: 'text',
                    value: 0
                });

            } else {
                this.infantsField = new Ext.form.Hidden ({
                    id : "infantsValue",
                    value: 0
                });
            }

            if (hidePersonsFeildset){
                this.personsFeildset = new Ext.form.FieldSet({
                    autoHeight: true,
                    layout: 'form',
                    autoWidth: true,
                    bodyBorder : false,
                    labelWidth: 190,
                    items:[
                        this.adultsField,
                        this.childrenField,
                        this.infantsField
                    ]
                });

                items.push(this.personsFeildset);
            }
            // end persons selection

            if(this.calendarStore){
                this.calendarField = new Ext.ensible.cal.CalendarCombo({
                    name: Ext.ensible.cal.EventMappings.CalendarId.name,
                    hidden: true,
                    anchor: '100%',
                    labelStyle: "display: none",
                    store: this.calendarStore
                });
                items.push(this.calendarField);
            }

            this.formPanel = new Ext.FormPanel({
                labelWidth: this.labelWidth,
                frame: false,
                bodyBorder: false,
                border: false,
                items: items
            });

            this.add(this.formPanel);
            Ext.ensible.cal.EventEditWindow.superclass.onRender.call(this, ct, position);
        },
        onSave: function(){

            if(!this.formPanel.form.isValid()){
                return;
            }

            // check the number of persons selection is ok...
            var peopleSelection = parseInt( Ext.getCmp("adultsValue").getValue(), 10) +
                parseInt( Ext.getCmp("childrenValue").getValue(), 10) +
                parseInt( Ext.getCmp("infantsValue").getValue(), 10);

            if (peopleSelection > parseInt( maxOccupancy, 10 )){
                Ext.Msg.alert('', RM.Translate.User.EnhancedCalendar.ExceededMaxOccupancy.replace(/\[XX]/g, maxOccupancy));
                return;
            }

            this.titleTextAdd = RM.Translate.User.EnhancedCalendar.YourSelection;

            this.fireEvent('eventadd', this, this.activeRecord, this.animateTarget);
            this.close();
        }
    });

    RM.Pages.Enhanced_Calendar_EventStore_Proxy = new Ext.data.HttpProxy({
        disableCaching: true, 
        api: {
            read: RM.Common.AssembleURL({
                controller : 'EnhancedCalendar',
                action: 'readJson',
                parameters: [
                    {
                        name: "unit_id", 
                        value: unitID
                    }
                ]
            }),
            create: RM.Common.AssembleURL({
                controller : 'EnhancedCalendar',
                action: 'createJson',
                parameters: [
                    {
                        name: "unit_id",
                        value: unitID
                    }
                ]
            }),
            update:  RM.Common.AssembleURL({
                controller : 'EnhancedCalendar',
                action: 'updateJson',
                parameters: [
                    {
                        name: "unit_id",
                        value: unitID
                    }
                ]
            }),
            destroy: RM.Common.AssembleURL({
                controller : 'EnhancedCalendar',
                action: 'deleteJson',
                parameters: [
                    {
                        name: "unit_id",
                        value: unitID
                    }
                ]
            })
        }
    });


    RM.Pages.Enhanced_Calendar_EventStore_Writer = new Ext.data.JsonWriter({
        encode: true,
        writeAllFields: false
    });

    // eventstore
    RM.Pages.Enhanced_Calendar_EventStore = Ext.extend(Ext.data.Store, {

        constructor: function(config){
            config = Ext.applyIf(config || {}, {
                storeId: 'eventStore',
                root: 'evts',
                proxy: RM.Pages.Enhanced_Calendar_EventStore_Proxy,
                writer: RM.Pages.Enhanced_Calendar_EventStore_Writer,
                fields: Ext.ensible.cal.EventRecord.prototype.fields.getRange(),
                idProperty: Ext.ensible.cal.EventMappings.EventId.mapping || 'id'
            });
            this.reader = new Ext.data.JsonReader(config);
            RM.Pages.Enhanced_Calendar_EventStore.superclass.constructor.call(this, config);

            if(config.autoMsg !== false){
                this.on('write', this.onWrite, this);
            }
        },

        onWrite: function(store, action, data, resp, rec){
            if(Ext.ensible.sample.msg){
                switch(action){
                    case 'create':
                        Ext.ensible.Calendar.msg('Add', 'Added "' + Ext.value(rec.data[Ext.ensible.cal.EventMappings.Title.name], '(No title)') + '"');
                        break;
                    case 'update':
                        Ext.ensible.Calendar.msg('Update', 'Updated "' + Ext.value(rec.data[Ext.ensible.cal.EventMappings.Title.name], '(No title)') + '"');
                        break;
                    case 'destroy':
                        Ext.ensible.Calendar.msg('Delete', 'Deleted "' + Ext.value(rec.data[Ext.ensible.cal.EventMappings.Title.name], '(No title)') + '"');
                        break;
                }
            }
        },

        onCreateRecords : function(success, rs, data) {
            rs.phantom = false;
            rs.data[Ext.ensible.cal.EventMappings.EventId.name] = rs.id;
            rs.commit();
        }
    });

    RM.Pages.Enhanced_Calendar_eventStoreData = function(){
        var conn = new Ext.data.Connection();
        var request = {
            url: RM.Common.AssembleURL({
                controller : 'EnhancedCalendar',
                action: 'getdataJson',
                parameters: [{
                    name: 'unit_id',
                    value: unitID
                }]
            }),
            method: 'GET',
            success: function(responseObject) {
                var json = Ext.util.JSON.decode(responseObject.responseText);

                this.eventStore = new RM.Pages.Enhanced_Calendar_EventStore({
                    data: json
                });

                RM.Pages.Enhanced_Calendar_main(this.eventStore);
            },
            failure: function(){
                Ext.Msg.alert('', RM.Translate.User.DatePicker.AJAXFailure);
                myMask.hide();
            }
        };
        conn.request(request);
    };
    
    RM.Pages.Enhanced_Calendar_eventStoreData();

    RM.Pages.Enhanced_Calendar_main = function(eventStore){

        try{
            Ext.getCmp("rm_enhanced_calendar").destroy();
        } catch (err){}

        this.eventStore = eventStore;

        RM.Pages.Enhanced_Calendar_CalendarStore = Ext.extend(Ext.data.Store, {
            constructor: function(config){
                config = Ext.applyIf(config || {}, {
                    storeId: 'calendarStore',
                    root: 'calendars',
                    idProperty: Ext.ensible.cal.CalendarMappings.CalendarId.mapping || 'id',
                    proxy: new Ext.data.MemoryProxy(),
                    autoLoad: true,
                    fields: Ext.ensible.cal.CalendarRecord.prototype.fields.getRange()
                });
                this.reader = new Ext.data.JsonReader(config);
                RM.Pages.Enhanced_Calendar_CalendarStore.superclass.constructor.call(this, config);
            }
        });

        this.calendarStore = new RM.Pages.Enhanced_Calendar_CalendarStore({
            data: {
                "calendars":[{
                    "id":2,
                    "title":RM.Translate.User.EnhancedCalendar.YourSelection,
                    "color":2
                },{
                    "id":1,
                    "title":RM.Translate.User.EnhancedCalendar.NotAvailable,
                    "color":22
                }]
            }
        });

        // if the price system does not allow hour selection then disable the day and week views
        if (!show_time){
            // hide days and weeks
            show_day = false;
            show_week = false;
        }

        new Ext.ensible.cal.CalendarPanel({
            id: 'rm_enhanced_calendar',
            eventStore: this.eventStore,
            calendarStore: this.calendarStore,
            renderTo: 'rm-enhanced-calendar-panel',
            title: unitName,
            activeItem: RM.Pages.EnhancedCalendar_SelectedView, // default to week view
            width: 700,
            height: 500,
            autoScroll: false,
            editModal: false,
            enableEditDetails: false,

            showTime: true,

            // config parameters
            readOnly: read_only,
            showDayView: show_day,
            showMonthView: show_month,
            showMultiWeekView: show_twoweek,
            showWeekView: show_week,

            // Standard Ext.Panel configs:
            frame: true,
            collapsible: false,
            bbar: [],

            listeners: {
                'eventclick': {
                    fn: function(panel, rec, el){
                        // disable event edit = return false
                        return false;
                    },
                    scope: this
                },
                'beforeeventmove': {
                    fn: function(panel ,rec){
                        return false;
                    },
                    scope: this
                },
                'beforeeventdelete': {
                    fn: function(panel, rec, el){
                        // disable event move = return false
                        return false;
                    },
                    scope: this
                },
                'editdetails': {
                    fn: function(panel, rec, el){
                        return false;
                    },
                    scope: this
                },
                'viewchange': {
                    fn: function(panel, rec, el){
                        RM.Pages.EnhancedCalendar_SelectedView = panel.activeView;
                        return false;
                    },
                    scope: this
                },
                'eventadd': {
                    fn: function(panel ,rec){

                        var nowVar = new Date().getTime();
                        if(( rec.data.StartDate.getTime() < nowVar) || (rec.data.StartDate.getTime() <nowVar )){
                            RM.Common.Message.msg(RM.Translate.User.DatePicker.DateSelection,RM.Translate.User.EnhancedCalendar.NotPermitted,3,"RM_popup_msg_div");
                            RM.Pages.Enhanced_Calendar_eventStoreData();
                            return;
                        }
                        
                        var myMask = new Ext.LoadMask('rm-enhanced-calendar-panel', {msg:RM.Translate.Common.PleaseWait});
                        myMask.show();

                        var adultsValue = parseInt(Ext.getCmp("adultsValue").getValue(),10);
                        var childrenValue = parseInt(Ext.getCmp("childrenValue").getValue(),10);
                        var infantsValue = parseInt(Ext.getCmp("infantsValue").getValue(),10);
                        var startdateVar, enddateVar;

                        if (!show_time){
                            // round up dates
                            var startDay = rec.data.StartDate.getDate();
                            var startMonth = rec.data.StartDate.getMonth()+1;
                            var startYear = rec.data.StartDate.getFullYear();
                            var endDay = rec.data.EndDate.getDate();
                            var endMonth = rec.data.EndDate.getMonth()+1;
                            var endYear = rec.data.EndDate.getFullYear();
                            
                            startdateVar = startYear + "-" + startMonth + "-" + startDay + " " + fullday_starttime;
                            enddateVar = endYear + "-" + endMonth + "-" + endDay + " " + fullday_endtime;
                        } else {
                            // do not round up
                            startdateVar = rec.data.StartDate.format(RM.Common.MySQLDateFormat); // yyyy-mm-dd hh:mm:ii
                            enddateVar = rec.data.EndDate.format(RM.Common.MySQLDateFormat); // yyyy-mm-dd hh:mm:ii
                        }

                        // Save the reservation Data
                        var conn = new Ext.data.Connection();
                        var request = {
                            url: RM.Common.AssembleURL({
                                controller : 'Reservations',
                                action: 'setdatecriteriaJson'
                            }),
                            params: {
                                unit_id : unitID,
                                startdate: startdateVar,
                                enddate: enddateVar,
                                adults: adultsValue,
                                children: childrenValue,
                                infants: infantsValue
                            },
                            method: 'POST',
                            success: function(responseObject) {
                                var json = Ext.util.JSON.decode(responseObject.responseText);
                                if (json.success===true){
                                    if (close_onselect){
                                        window.parent.location.reload();
                                    } else {
                                        RM.Pages.Enhanced_Calendar_eventStoreData();
                                        myMask.hide();
                                    }
                                } else {
                                    RM.Common.Message.msg(RM.Translate.User.DatePicker.DateSelection,RM.Translate.User.EnhancedCalendar.NotPermitted,3,"RM_popup_msg_div");
                                    RM.Pages.Enhanced_Calendar_eventStoreData();
                                    myMask.hide();
                                }
                            },
                            failure: function(){
                                Ext.Msg.alert('', RM.Translate.User.DatePicker.AJAXFailure);
                                myMask.hide();
                            }
                        };
                        conn.request(request);
                    },
                    scope: this
                }
            }
        });

        if (calendarStartDate == ""){
            calendarStartDate = new Date();
        } else {
            calendarStartDate = RM.Common.ConvertToDate(calendarStartDate);
        }


        Ext.getCmp("rm_enhanced_calendar").setStartDate(calendarStartDate);

        if (show_help_popup) {
            RM.Common.Message.msg(
                RM.Translate.User.DatePicker.DateSelection,
                RM.Translate.User.EnhancedCalendar.SelectionTip,
                3,"RM_popup_msg_div"
            );
        }
    };
});